from django.conf import settings
from django.db.models import Avg, Sum, Count, Max, Min, Q, F
from django.forms.models import model_to_dict

from rest_framework import serializers
from rest_framework.serializers import *
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator  # 验证器

from datetime import datetime, date, timedelta, timezone
import time

# from allinpay import apidev as PAY
from mysqldb.models import *

# from CallManager.serializers import AllinpayCallmeListSerializer

# from mysqldb import redis as REDIS


class NoneSerializer(serializers.Serializer):
    """无序列化"""

    class Meta:
        fields = "__all__"


class PlaceSerializer(serializers.Serializer):
    """场所序列化"""

    pid = IntegerField(allow_null=True, required=True, help_text="场所ID")

    class Meta:
        fields = "__all__"

    def validate(self, attrs):
        try:
            r = AllinpayPlaceList.objects.get(id=attrs.get("pid"), status=1)
        except BaseException as err:
            raise serializers.ValidationError("场所不存在")
        return attrs


class AllinpayReportWorkListSerializer(serializers.Serializer):
    """工作项统计报表"""

    rptype = ChoiceField(choices=[(1, "工作项标题"), (2, "工作项执行人")], help_text="报表类型")
    pid = ListField(child=IntegerField(), help_text="场所ID")
    star = DateField(required=False, default=date.today, help_text="开始日期")
    stop = DateField(required=False, default=date.today, help_text="截止日期")
    # rwtype = IntegerField(required=False, help_text="奖励模块")

    class Meta:
        fields = "__all__"

    def validate_pid(self, attr):
        for i in attr:
            try:
                r = AllinpayPlaceList.objects.get(id=i, status=1)
            except BaseException as err:
                raise serializers.ValidationError("场所不存在或未启用")
        return attr


class AllinpayReportInterListSerializer(serializers.Serializer):
    """得分统计报表"""

    rptype = ChoiceField(choices=[(1, "场所统计"), (2, "员工统计")], help_text="报表类型")
    pid = ListField(child=IntegerField(), help_text="场所ID")
    star = DateField(required=False, default=date.today, help_text="开始日期")
    stop = DateField(required=False, default=date.today, help_text="截止日期")

    class Meta:
        fields = "__all__"

    def validate_pid(self, attr):
        for i in attr:
            try:
                r = AllinpayPlaceList.objects.get(id=i, status=1)
            except BaseException as err:
                raise serializers.ValidationError("场所不存在或未启用")
        return attr


# ============================================
# 凡商商品订单
# ============================================


class FsygPchardListSerializer(serializers.ModelSerializer):
    """终端分组序列化"""

    # groups = SerializerMethodField()

    class Meta:
        model = FsygPchardList
        fields = "__all__"

    # def get_groups(self, obj):
    #     r = (
    #         FsygPchardList.objects.filter(pid=obj.pid)
    #         .values_list("group", flat=True)
    #         .distinct()
    #     )
    #     return r


class FsygPchardListSerializer(serializers.ModelSerializer):
    """终端序列化"""

    class Meta:
        model = FsygPchardList
        fields = "__all__"


class FsygShopintoListSerializer(serializers.ModelSerializer):
    """凡商商品流水"""

    class Meta:
        model = FsygShopintoList
        fields = "__all__"


class FsygShopreqsnListSerializer(serializers.ModelSerializer):
    """凡商商品订单流水"""

    products = SerializerMethodField()
    # callme = SerializerMethodField()

    class Meta:
        model = FsygShopreqsnList
        fields = "__all__"

    def get_products(self, attr):
        r = FsygShopintoList.objects.filter(order=attr.reqsn)
        return FsygShopintoListSerializer(r, many=True).data

    # def get_callme(self, attr):
    #     try:
    #         r = AllinpayCallmeList.objects.get(id=attr.delivery)
    #     except BaseException as err:
    #         return None
    #     else:
    #         return model_to_dict(r)
    # return AllinpayCallmeListSerializer(r).data


class FsygMemberListSerializer(serializers.ModelSerializer):
    """凡商场所会员列化"""

    class Meta:
        model = FsygMemberList
        fields = "__all__"


# =================================================================
# 凡商商品同比报表
# =================================================================


class ReportTermLimitSerializer(serializers.Serializer):
    """报表范围序列化"""

    year = IntegerField(allow_null=True, help_text="年份")
    month = IntegerField(allow_null=True, help_text="月份")
    day = IntegerField(allow_null=True, help_text="日期")
    week = IntegerField(allow_null=True, help_text="周")
    pid = IntegerField(allow_null=True, help_text="场所ID")

    class Meta:
        fields = "__all__"

    def is_leap_year(self, year):
        """判断是否为闰年"""
        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
            return True
        else:
            return False

    def get_days_by_month(self, year, month):
        """判断当月天数"""
        if month == 2:
            days = 29 if self.is_leap_year(year) else 28
        elif month in [4, 6, 9, 11]:
            days = 30
        else:
            days = 31
        return days

    def validate(self, attrs):
        if attrs["year"]:
            if attrs["year"] < 2023:
                raise serializers.ValidationError("年份不能小于2016")
        if attrs["month"]:
            if not attrs["year"]:
                raise serializers.ValidationError("缺少年份")
            if attrs["month"] > 12:
                raise serializers.ValidationError("月份不能大于12")
        if attrs["day"]:
            if not attrs["year"]:
                raise serializers.ValidationError("缺少年份")
            if not attrs["month"]:
                raise serializers.ValidationError("缺少月份")
            if attrs["day"] > self.get_days_by_month(
                abs(attrs["year"]), abs(attrs["month"])
            ):
                raise serializers.ValidationError("日期太大了")
        if attrs["week"]:
            if not attrs["year"]:
                raise serializers.ValidationError("缺少年份")
            if attrs["week"] > 52:
                raise serializers.ValidationError("周不能大于52")
        # 验证场所
        try:
            r = AllinpayPlaceList.objects.get(id=attrs["pid"], status=1)
        except BaseException as err:
            raise serializers.ValidationError("场所不存在")

        return attrs
